package com.lwm.demo.utils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 数据库连接工具类
 *
 * @author liweimin
 * @date 2021/6/10 16:02
 * @since
 */
public class ConnectionUtils {
    private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    private DataSource dataSource;

    public ConnectionUtils() {
    }

    public ConnectionUtils(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public Connection getConnection() {
        Connection connection = threadLocal.get();
        if (connection == null) {
            try {
                connection = dataSource.getConnection();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            threadLocal.set(connection);
        }
        return connection;
    }


    public void removeConnection() {
        threadLocal.remove();
    }
}
